﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SISLOG.BusinessEntities;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using System.Data.Common;
using Microsoft.Practices.Unity;

namespace SISLOG.DataAccess
{
    public class OrdenCompraDAO: MasterDAEL, IOrdenCompraDAO
    {
        [Dependency]
        public IDetalleOrdenCompraDAO DetalleOrdenCompraDAO { get; set; }

        public List<OrdenCompra> GetAllFromOrdenCompra()
        {
            var query = dbSisLog.ExecuteSprocAccessor<OrdenCompra>("GetAllFromOrdenCompra", RowMapperFactory());
            return query.ToList();
        }

        public IRowMapper<OrdenCompra> RowMapperFactory()
        {
            IRowMapper<OrdenCompra> rowMapper = MapBuilder<OrdenCompra>
                                                .MapAllProperties()
                                                .Map(p => p.DetalleOrdenCompra)
                                                .WithFunc(p => DetalleOrdenCompraDAO.GetFromDetalleOrdenCompraByOrdenId(p.GetInt32(p.GetOrdinal("idOrdenCompra"))))
                                                .Build();
            return rowMapper;            
        }

        public OrdenCompra GetFromOrdenCompraById(int idOrdenCompra)
        {
            var query = dbSisLog.ExecuteSprocAccessor<OrdenCompra>("GerFromOrdenCompraById", RowMapperFactory(), idOrdenCompra);
            return query.SingleOrDefault();
        }

        public void RealizarOrdenCompra(OrdenCompra ordencompra)
        {
            DbCommand command = dbSisLog.GetStoredProcCommand("RealizarOrdenCompra");

            DbParameter param = command.CreateParameter();

            param.Direction = System.Data.ParameterDirection.InputOutput;
            param.ParameterName = "id";
            param.DbType = System.Data.DbType.Int32;
            param.Value = ordencompra.idOrdenCompra;

            command.Parameters.Add(param);

            dbSisLog.AddInParameter(command, "idOrdenCompra", System.Data.DbType.Int32, ordencompra.idOrdenCompra);
            dbSisLog.AddInParameter(command, "fecha", System.Data.DbType.DateTime, ordencompra.fechaOrdenCompra);
            dbSisLog.AddInParameter(command, "responsable", System.Data.DbType.String, ordencompra.responsable);

            dbSisLog.ExecuteNonQuery(command);

            ordencompra.idOrdenCompra = Int32.Parse(param.Value.ToString());

            DetalleOrdenCompraDAO.RegistrarDetalleOrdenCompra(ordencompra.DetalleOrdenCompra, ordencompra.idOrdenCompra);
        }
    }
}
